package service

import (
	"github.com/vueadmin/app/admin/dto"
	"github.com/vueadmin/app/admin/model"
	"github.com/vueadmin/global"
	"github.com/vueadmin/utils/conv"
)

var AdminBaseService = new(adminBaseService)

type adminBaseService struct{}

// 获取当前角色的左侧菜单
func (p adminBaseService) GetMenu() []*model.Node {
	var data []*model.Node
	data = p.getBaseMenus()
	return data
}

// 获取左侧菜单
func (p adminBaseService) getBaseMenus() []*model.Node {
	var data []*model.Node
	if err := global.DB.Model(&model.Node{}).Where("type", 1).Where("status", 1).Order("sortid asc").Find(&data).Error; err != nil {
		panic(err)
	}
	return p.getTreeMenu(data, 0)
}

func (p adminBaseService) getTreeMenu(list []*model.Node, parentId int) []*model.Node {
	res := make([]*model.Node, 0)
	for _, v := range list {
		if int(v.Pid) == parentId {
			v.Children = p.getTreeMenu(list, int(v.NodeId))
			if v.Icon == "" {
				v.Icon = "el-icon-menu"
			}
			res = append(res, v)
		}
	}
	return res
}

// 获取需要渲染的组件
func (p adminBaseService) GetComponents() []map[string]interface{} {
	var (
		param      []*model.Node
		components []map[string]interface{}
	)
	if err := global.DB.Model(&model.Node{}).Where("type", 1).Where("status", 1).Where("component_path != ?", "").Order("sortid asc").Find(&param).Error; err != nil {
		panic(err)
	}
	for _, val := range param {
		components = append(components, map[string]interface{}{
			"name":           val.Path,
			"path":           val.Path,
			"component_path": val.ComponentPath,
			"meta":           map[string]interface{}{"title": val.Title},
		})
	}
	return components
}

// 修改密码
func (p adminBaseService) ResetPwd(req *dto.AdminResetPwdReq, user_id interface{}) error {
	return global.DB.Model(&model.AdminAdminuser{}).Where("user_id = ?", user_id).Update("pwd", conv.EncryptPassword(req.Password)).Error
}
